package com.sum.tea.rongrui

import android.Manifest
import android.app.Activity
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import androidx.core.app.ActivityCompat
import androidx.lifecycle.Observer
import androidx.lifecycle.lifecycleScope
import com.blankj.utilcode.util.ConvertUtils
import com.sum.common.base.BaseMvvmActivity
import com.sum.tea.databinding.ActivityFstBinding
import com.sum.tea.rongrui.viewmodel.FSTViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.io.File
import java.io.IOException

class FSTActivity :  BaseMvvmActivity<ActivityFstBinding, FSTViewModel>() {

    override fun initView(savedInstanceState: Bundle?) {
        checkAndRequestPermission()
        // 观察ViewModel中的LiveData
        mViewModel.result.observe(this, Observer { result ->
            mBinding.fstResult.text = result
        })

        mViewModel.buttonsEnabled.observe(this, Observer { enabled ->
            mBinding.buttonFstTran.isEnabled = enabled
            mBinding.buttonFstShow.isEnabled = enabled
        })
        setListener()
    }

    private fun setListener(){
        mBinding.buttonFstSelect.setOnClickListener {
            val intent = Intent(Intent.ACTION_GET_CONTENT).apply {
                putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true)
                type = "text/plain"
                addCategory(Intent.CATEGORY_OPENABLE)
            }
            startActivityForResult(Intent.createChooser(intent, "选择文件"), 101)
        }
        mBinding.buttonFstTran.setOnClickListener{
            mViewModel.transImage()
        }
        mBinding.buttonFstShow.setOnClickListener{
            mViewModel.showImage(mBinding.fstSpinner.selectedItem as? String)
        }
    }

    override fun onResume() {
        super.onResume()
        mViewModel.loadEPCData()
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == 101 && resultCode == Activity.RESULT_OK && data != null) {
            val uri = data.data ?: return
            val path = uri.path ?: return
            val file = File(path)
            if (file.exists()) {
                lifecycleScope.launch {
                    try {
                        val reds = withContext(Dispatchers.IO) {
                            file.readText().lineSequence()
                                .filter { it.isNotEmpty() }
                                .map { it.split("+")[0] }
                                .lastOrNull() ?: ""
                        }
                        if (reds.isNotEmpty()) {
                            mViewModel.setTranData(ConvertUtils.hexString2Bytes(reds))
                            mViewModel.sendMessage("图片已选择", 0x01)
                        }
                    } catch (e: IOException) {
                        mViewModel.sendMessage("图片选择失败", 0x01)
                        e.printStackTrace()
                    }
                }
            }
        }
    }

    private fun checkAndRequestPermission() {
        if (Build.VERSION.SDK_INT >= 23) {
            val lackedPermission = mutableListOf<String>()
            if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                lackedPermission.add(Manifest.permission.READ_EXTERNAL_STORAGE)
            }

            if (lackedPermission.isNotEmpty()) {
                ActivityCompat.requestPermissions(this, lackedPermission.toTypedArray(), 1)
            }
        }
    }

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == 102) {
            val deniedPermissions = mutableListOf<String>()
            val grantedPermissions = mutableListOf<String>()
            grantResults.forEachIndexed { index, grantResult ->
                if (grantResult != PackageManager.PERMISSION_GRANTED) {
                    deniedPermissions.add(permissions[index])
                } else {
                    grantedPermissions.add(permissions[index])
                }
            }
            if (deniedPermissions.isEmpty()) {
                // 权限全部授予
            } else {
                // 处理未授予的权限
            }
        }
    }
}
